import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList; 
import oracle.jdbc.pool.OracleDataSource;
//gethouses servlet displays the houses that are stored in the database in an html table
public class getHouses extends HttpServlet
{
	public static dbapi conn;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(htmlHeader.header);
		conn = new dbapi();
		//connect to oracle
		conn.connect();
		if(!conn.connected)//if the connection does not work, inform the user w/ error message
		{
			out.println("SQL ERROR CANNOT CONNECT TO DATABASE!<br>");
			out.println(conn.msg + "<br>");
			return;
		}
		int ct = 0;
		
		ct = conn.getHomeCount();//set the variable ct equal to the HomeCount of the database
		if(ct == -1)//if ct = -1, inform the user there are no houses in the database
		{
			out.println("No houses in database. <br>"+conn.msg);
			return;
		}
		//else
		//	out.println(ct+" houses in database.<br>");

		ArrayList<home> houseList = conn.getAllHomes();//create an array containing each of the houses in the database
		
		if(houseList == null)//if the house list array is null, output error message
		{
			out.println("Error: null resultset from database<br>"+conn.msg);
			return;
		}
		else//else do the following
		{
			//create an html table
			out.println("<p style=\"font-size:20pt;\">Houses</p>"+
					"<table border=1 width=100%><tr>"+
				    "<th width=25%>Address</th>"+
				    "<th width=20%>City</th>"+
				    "<th width=15%>State</th>"+
				    "<th width=10%>Zipcode</th>"+
				    "<th width=30%></th>"
				     );
			//for each house in the arraylist, print the following data into the html table
			for(int i=0;i<houseList.size();i++)
			{
				out.println("<tr>");
				out.println("<td>"+houseList.get(i).address+"</td>");
				out.println("<td>"+houseList.get(i).city+"</td>");
				out.println("<td>"+houseList.get(i).state+"</td>");
				out.println("<td>"+Integer.toString(houseList.get(i).zipcode)+"</td>");
				out.println("<td><a href=\"houseDetails?id="+Integer.toString(houseList.get(i).id)+"\">View House</a><br><a href=\"addAppliance?id="+Integer.toString(houseList.get(i).id)+"\">Add Appliance</a><br>");
				
				//if the house is not on the market, display a hotlink to the add house to market servlet
				if(!conn.isHouseOnMarket(houseList.get(i).id))	
					out.println("<a href=\"addMarket?id="+Integer.toString(houseList.get(i).id)+"\">Add to Market</a><br>");
				//display a hotlink to the delete home servlet
				out.println("<a href=\"delHome?id="+Integer.toString(houseList.get(i).id)+"\">Delete Home</a></td>");
				out.println("</tr>");
			}
			out.println("</table>");
		}
	}
}
